package com.example.himalaya.presenters;

import com.example.himalaya.model.api.OnDemandDataApi;
import com.example.himalaya.constants.Constants;
import com.example.himalaya.presenters.interfaces.IAlbumDetailPresenter;
import com.example.himalaya.view.callback.IAlbumDetailViewCallback;
import com.example.himalaya.utils.LogUtil;
import com.ximalaya.ting.android.opensdk.datatrasfer.IDataCallBack;
import com.ximalaya.ting.android.opensdk.model.album.Album;
import com.ximalaya.ting.android.opensdk.model.track.Track;
import com.ximalaya.ting.android.opensdk.model.track.TrackList;

import java.util.ArrayList;
import java.util.List;

public class AlbumDetailPresenter implements IAlbumDetailPresenter {

    // Constant
    private static final String TAG = ".presenters.AlbumDetailPresenter";


    // Tool
    private List<IAlbumDetailViewCallback> mCallbacks = new ArrayList<>();
    private List<Track> mTracks = new ArrayList<>();        // 当前获得的所有数据

    private Album mTargetAlbum;

    private int mCurrentAlbumId = -1;
    private int mCurrentAlbumPageIndex = Constants.DEFAULT_PAGE;


    private AlbumDetailPresenter() {

    }

    private static AlbumDetailPresenter sInstance = null;

    public static AlbumDetailPresenter getInstance() {
        if (sInstance == null) {
            synchronized (AlbumDetailPresenter.class) {
                sInstance = new AlbumDetailPresenter();
            }
        }

        return sInstance;
    }

    @Override
    public void pull2RefreshMore() {

    }

    @Override
    public void loadMore() {
        // 去加载更多内容
        mCurrentAlbumPageIndex++;
        // true 上拉， false 下拉
        doLoaded(true, Constants.LOAD_MORE_TRACK);
    }

    private void doLoaded(final boolean isLoaderMore, int load_number) {

        if (!isLoaderMore) {
            mCurrentAlbumPageIndex = Constants.DEFAULT_PAGE;
        }

        OnDemandDataApi onDemandDataApi = OnDemandDataApi.getOnDemandDataApi();

        onDemandDataApi.getTracks(mCurrentAlbumId, mCurrentAlbumPageIndex, load_number, new IDataCallBack<TrackList>() {
            @Override
            public void onSuccess(TrackList trackList) {
                // 获取当前线程的名字，判断是否是主线程，从而决定是否跟新UI
                // LogUtil.d(TAG, "Current Thread -->" + Thread.currentThread().getName());
                if (trackList != null) {
                    List<Track> tracks = trackList.getTracks();
                    // LogUtil.d(TAG, "tracks size --> " + tracks.size());
                    if (isLoaderMore) {
                        // 将新获得的数据放到列表最后
                        // 上拉加载
                        mTracks.addAll(tracks);

                        // 加载回来的结果广播
                        for (IAlbumDetailViewCallback callback : mCallbacks) {
                            callback.onLoaderMoreFinished(tracks.size());
                        }

                    } else {
                        // 将新获得的数据放到列表前面
                        // 下拉加载
                        mTracks.addAll(0, tracks);
                    }
                    handlerAlbumDetailResult(mTracks);
                }
            }

            @Override
            public void onError(int errorCode, String errorMsg) {
                LogUtil.d(TAG, "errorCode -->  " + errorCode);
                LogUtil.d(TAG, "errorMsg -->  " + errorMsg);

                if (isLoaderMore) {
                    mCurrentAlbumPageIndex--;
                }

                handlerError(errorCode, errorMsg);
            }
        });

    }

    @Override
    public void getAlbumDetail(int albumId, int page) {
        mTracks.clear();
        this.mCurrentAlbumId = albumId;
        this.mCurrentAlbumPageIndex = page;
        // 根据页码和专辑id获取列表

        doLoaded(false, Constants.COUNT_DEFAULT);
    }


    private void handlerError(int errorCode, String errorMsg) {
        for (IAlbumDetailViewCallback callback : mCallbacks) {
            callback.onNetworkError(errorCode, errorMsg);
        }
    }


    /**
     * 通过注册的回调列表分发得到的数据
     *
     * @param tracks 请求回来的数据
     */
    private void handlerAlbumDetailResult(List<Track> tracks) {
        for (IAlbumDetailViewCallback callback : mCallbacks) {
            callback.onDetailListLoaded(tracks);
        }
    }

    @Override
    public void registerViewCallback(IAlbumDetailViewCallback detailViewCallback) {

        if (!mCallbacks.contains(detailViewCallback)) {
            mCallbacks.add(detailViewCallback);

            if (mTargetAlbum != null) {
                detailViewCallback.onAlbumLoaded(mTargetAlbum);
            }
        }

    }

    @Override
    public void unRegisterViewCallback(IAlbumDetailViewCallback detailViewCallback) {
        mCallbacks.remove(detailViewCallback);
    }


    public void setTargetAlbum(Album targetAlbum) {
        this.mTargetAlbum = targetAlbum;

    }
}
